package com.iflytek.ossp.mrecharge.ssmsgw.start.context;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.config.ConfigFileApplicationListener;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;

import java.io.File;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Desc: 修改默认配置文件搜索路径
 * Author: ljdong2
 * Date: 2018/3/23
 * 修改ConfigFileApplicationListener中默认配置文件搜索路径为  classpath:config/${spring.profiles.active}/
 */
public class DefaultSearchLocationConfigListener implements EnvironmentPostProcessor, Ordered {
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        String[] activeProfiles = environment.getActiveProfiles();
        String profile = activeProfiles[0];
        Set<ApplicationListener<?>> listeners = application.getListeners();
        ConfigFileApplicationListener applicationListener1 = (ConfigFileApplicationListener) listeners.stream()
                .filter(applicationListener -> applicationListener.getClass() == ConfigFileApplicationListener.class)
                .collect(Collectors.toList()).get(0);
        applicationListener1.setSearchLocations("classpath:/config" + File.separator + profile + File.separator);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}